package br.com.findme.findmeserver.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.SessionFactoryObserver;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;

import br.com.findme.findmeserver.entidade.Grupo;
import br.com.findme.findmeserver.entidade.Localizacao;
import br.com.findme.findmeserver.entidade.Mensagem;
import br.com.findme.findmeserver.entidade.Usuario;

public class HibernateUtils {
    
   private static final SessionFactory factory;
   private static final ServiceRegistry serviceRegistry;
    
    static {
        Configuration config = getConfiguration();
        
        serviceRegistry = new ServiceRegistryBuilder().applySettings(
                config.getProperties()).buildServiceRegistry();
        
        config.setSessionFactoryObserver(new SessionFactoryObserver() {

            private static final long serialVersionUID = 1L;

			@Override
            public void sessionFactoryCreated(SessionFactory factory) { }

            @Override
            public void sessionFactoryClosed(SessionFactory factory) {
                ServiceRegistryBuilder.destroy(serviceRegistry);
            }
        });
        
        factory = config.buildSessionFactory(serviceRegistry);
    } 
    
    private static Configuration getConfiguration() {
    
        Configuration cfg = new Configuration();
        cfg.configure("META-INF/hibernate.cfg.xml");
        cfg.addAnnotatedClass(Usuario.class);
        cfg.addAnnotatedClass(Grupo.class);
        cfg.addAnnotatedClass(Localizacao.class);
        cfg.addAnnotatedClass(Mensagem.class);        
        return cfg;
    }
    
    public static Session openSession() {
        return factory.openSession();
    }
    
   
    public static void createOrUpdateSchema(boolean script, boolean doUpdate) {
        
        SchemaUpdate schema = new SchemaUpdate(getConfiguration());
        schema.execute(script, doUpdate);
    }
  
}
